package com.defysoft.waukidsbus.start;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukidsbus.BaseActivity;
import com.defysoft.waukidsbus.Data_Type.StartBus;
import com.defysoft.waukidsbus.JsonParser;
import com.defysoft.waukidsbus.R;
import com.defysoft.waukidsbus.Sqlite_Connect;

public class Start_ScanMode extends BaseActivity {
	Toolbar toolbar;

	private BluetoothAdapter mBluetoothAdapter;
	private static final int REQUEST_ENABLE_BT = 3;
	private boolean checklist;
	private Handler mHandler;
	int checkmode = 0;
	final int SUCCESS = 10;
	final int SUBSUCCESS = 9;
	final int THREESUCCESS = 7;
	final int FAIR = 8;
	final int END = 6;
	GridView gridView;
	ImageView stop;
	ArrayList<String> settinglist;
	ArrayList<StartBus> list;
	TextView tv;
	int changcode = 0;
	String param = null;
	ArrayList<StartBus> newlist;
	boolean onoff = true;
	boolean checkonoff = true;
	private long SCAN_PERIOD = 10000;
	private SharedPreferences login_code;
	String code, Gob_Name;
	StartAdapter startAdapter;
	Sqlite_Connect sc;
	RelativeLayout RL;
	TextView err;
	TextView normal;
	TextView close;
	ListView log;
	LogAdapter logAdapter;
	ArrayList<String> loglist;
	Cursor cursor;
	Cursor savelog;
	int scancount = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start__scan_mode);
		setStartData();
		setstartLog();
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {// ���������������üũ

		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) { // ������� ������
				// Bluetooth is now enabled, so set up a chat session
				Toast.makeText(this, "블루투스 사용가능", Toast.LENGTH_LONG).show();
				scanLeDevice(true);
			} else { // ������� ������ ���� �����佺Ʈ ���� ��
				// User did not enable Bluetooth or an error occurred
				Toast.makeText(this, "블루투스 사용불가", Toast.LENGTH_LONG).show();
				finish();
			}
		}
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		if (checkmode == 0) {
			stop.callOnClick();
		} else if (checkmode == 1) {
			stop.callOnClick();
		} else {
			super.finish();
		}
	}

	public void setstartLog() {
		RL = (RelativeLayout) findViewById(R.id.START_SCAN_RL);
		err = (TextView) findViewById(R.id.START_SCAN_LOG_ERR);
		log = (ListView) findViewById(R.id.START_SCAN_LOG);
		loglist = new ArrayList<String>();
		logAdapter = new LogAdapter();
		log.setAdapter(logAdapter);
		normal = (TextView) findViewById(R.id.START_SCAN_LOG_NORMAR);
		close = (TextView) findViewById(R.id.START_SCAN_LOG_EXIT);
		normal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loglist = new ArrayList<String>();
				if (cursor != null) {
					cursor.close();
				}
				cursor = sc.check_GO_BUS();
				while (cursor.moveToNext()) {
					loglist.add(cursor.getString(0)
							+ (cursor.getInt(2) % 2 == 1 ? cursor.getInt(2)
									+ "  # " : cursor.getInt(2) + "  @ ")
							+ cursor.getString(1));
				}
				logAdapter.notifyDataSetChanged();
				RL.setVisibility(View.VISIBLE);
			}
		});
		err.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loglist = new ArrayList<String>();
				if (cursor != null) {
					cursor.close();
				}
				cursor = sc.check_GO_BUS(1);
				while (cursor.moveToNext()) {
					loglist.add(cursor.getString(0) + "  # "
							+ cursor.getString(1));
				}
				logAdapter.notifyDataSetChanged();
				RL.setVisibility(View.VISIBLE);
			}
		});
		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				RL.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		Gob_Name = getIntent().getStringExtra("Gob_Name");
		try {
			SCAN_PERIOD = (Integer.parseInt(getIntent()
					.getStringExtra("second")) * 1000);
		} catch (Exception e) {
			SCAN_PERIOD = 1000;
		}
		sc = new Sqlite_Connect(this);
		tv = (TextView) findViewById(R.id.START_SCAN_STATE);
		code = getIntent().getStringExtra("code");
		mHandler = new Handler();
		stop = (ImageView) findViewById(R.id.START_SCAN_STOP);
		gridView = (GridView) findViewById(R.id.START_SCAN_GRID);
		login_code = getSharedPreferences("login_code", MODE_PRIVATE);
		toolbar = (Toolbar) findViewById(R.id.START_SCAN_TOOL);

		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		stop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (checkmode == 0) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Start_ScanMode.this);
					builder.setMessage(Gob_Name + " 버스의 운행을 종료합니다.")
							.setCancelable(false)
							.setPositiveButton("확인",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											checkmode = 1;
											((TextView) findViewById(R.id.START_SCAN_TITLE))
													.setText("운\t행\t종\t료");
											stop.setImageResource(R.drawable.stop_bus_endt);
											scanLeDevice(false);
											
										}
									})
							.setNegativeButton("취소",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Start_ScanMode.this);
					builder.setMessage("등원모드를 종료합니다.")
							.setCancelable(false)
							.setPositiveButton("확인",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											checkmode = 2;
											stop.setVisibility(View.INVISIBLE);
											checkScanLeDevice(false);
											startThread(4);
										}
									})
							.setNegativeButton("취소",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();

				}
			}
		});
		startThread(1);
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (cho) {
				case 1:
					mainThread();
					break;
				case 2:
					subThread();
					break;
				case 3:
					threeThread();
					break;
				case 4:
					fourThread();
					break;
				}
			}
		});
		firstThread.start();
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			sc.insert_GO_BUS("통신상태 에러발생", 3);
			break;
		case FAIR:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			sc.insert_GO_BUS("원생정보를 얻지 못했습니다.(서버문제)", 3);
			break;
		case SUCCESS:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			list = JsonParser.StartScanMode((String) _message.obj);
			startAdapter = new StartAdapter();
			gridView.setAdapter(startAdapter);
			if (!getPackageManager().hasSystemFeature(
					PackageManager.FEATURE_BLUETOOTH_LE)) {
				Toast.makeText(this, "ble��� ���Ұ����� db�Դϴ�.",
						Toast.LENGTH_SHORT).show();
				finish();
			}

			final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
			mBluetoothAdapter = bluetoothManager.getAdapter();
			if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
				Intent enableBtIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			} else {
				sc.insert_GO_BUS("등원버스 스캔정상시작", 2);
				scanLeDevice(true);
			}
			break;
		case SUBSUCCESS:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			if (_message.obj.equals("aset")) {
				Toast.makeText(this, "네트워크 상태를 확인하세요", Toast.LENGTH_SHORT)
						.show();
			}
			if (onoff) {
				cursor = sc.check_GO_BUS();

				scanLeDevice(true);
			} else {

				checkScanLeDevice(true);
			}
			break;
		case THREESUCCESS:
			endDIal();
			break;
		case END:
			endDIal();
			finish();
			break;
		}
	}

	private void scanLeDevice(final boolean enable) {
		newlist = new ArrayList<StartBus>();
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					if (onoff) {
						/*
						 * Toast.makeText(Start_ScanMode.this,"스캔완료" +
						 * newlist.size(), Toast.LENGTH_SHORT).show();
						 */
						Toast.makeText(Start_ScanMode.this, "Search",
								Toast.LENGTH_SHORT).show();
						startAdapter.notifyDataSetChanged();
						startThread(2);
					}
				}
			}, SCAN_PERIOD);
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			onoff = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);

			tv.setText("운행이 종료되었습니다. 남은아이가 있는지 검사를 시작합니다.");
			startThread(2);

		}
	}

	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			final int rss = rssi;
			final byte[] scan = scanRecord;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					for (int i = 0; i < list.size(); i++) {
						if (device.getAddress().equals(list.get(i).bea_id)) {
							if (list.get(i).checkon == false) {
								newlist.add(list.get(i));
								list.get(i).checkon = true;
								list.get(i).rssi = rss + "";
							}
						}
					}
				}
			});
		}
	};

	private void checkScanLeDevice(final boolean enable) {

		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mBluetoothAdapter.stopLeScan(mCheckLeScanCallback);
					if (checkonoff) {
						int endcheck = 0;

						for (int i = 0; i < list.size(); i++) {
							list.get(i).checkon = false;
						}
						for (int i = 0; i < list.size(); i++) {
							for (int j = 0; j < newlist.size(); j++) {
								if (list.get(i).bea_id.equals(newlist.get(j).bea_id)) {
									list.get(i).checkon = true;
									newlist.remove(j);
									break;
								}
							}
						}

						for (int i = 0; i < list.size(); i++) {
							if (list.get(i).checkon == true) {
								endcheck++;
							}
						}

						if (endcheck == 0) {
							tv.setText("비콘이 감지되지 않습니다. Search...");
						} else {
							Uri notification = RingtoneManager
									.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
							Ringtone r = RingtoneManager.getRingtone(
									getApplicationContext(), notification);
							r.play();
							tv.setText(endcheck + "명이 아직 버스에 남아있습니다. Search...");
						}

						// ((TextView)findViewById(R.id.START_SCAN_TITLE)).setText(endcheck);
						startAdapter.notifyDataSetChanged();

						checkScanLeDevice(true);
					}
				}
			}, SCAN_PERIOD);
			newlist = new ArrayList<StartBus>();
			mBluetoothAdapter.startLeScan(mCheckLeScanCallback);
		} else {
			checkonoff = false;
			mBluetoothAdapter.stopLeScan(mCheckLeScanCallback);
			Toast.makeText(this, "기능종료", Toast.LENGTH_SHORT).show();
		}
	}

	private BluetoothAdapter.LeScanCallback mCheckLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			final int rss = rssi;
			final byte[] scan = scanRecord;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					boolean check = true;
					for (int i = 0; i < newlist.size(); i++) {
						if (newlist.get(i).bea_id.equals(device.getAddress())) {
							check = false;
						}
					}
					if (check) {
						for (int i = 0; i < list.size(); i++) {
							if (device.getAddress().equals(list.get(i).bea_id)) {
								newlist.add(list.get(i));
							}
						}
					}
				}
			});
		}
	};

	protected void mainThread() {
		// TODO Auto-generated method stub
		String msg = "";
		try {
			Log.i("ccc", code);
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_SCANMODE_START,
					"code=" + code /*+ "&sth="
							+ login_code.getString("sch_code", null)*/));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				onNetworkCallback(SUCCESS, msg);
			} else {
				onNetworkCallback(FAIR, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
		;
	}

	protected void subThread() { // GCM보내기 스레드
		// TODO Auto-generated method stub
		String msg = "";
		scancount++;
		try {
			for (int i = 0; i < newlist.size(); i++) {
				if (param == null) {
					param = newlist.get(i).stu_code;
				} else {
					param += ("-" + newlist.get(i).stu_code);
				}
			}
			for (int i = 0; i < newlist.size(); i++) {
				sc.insert_GO_BUS(newlist.get(i).stu_name + "의 비콘 최초인식 "
						+ newlist.get(i).rssi, 2);
			}

			if (isNetworkStat(this)) {

				if (scancount % 5 == 0) {
					if ((savelog = sc.save_GO_BUS()).getCount() > 0) {
						String logstr = null;
						while (savelog.moveToNext()) {
							if (logstr == null) {
								logstr = savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							} else {
								logstr += "," + savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							}

						}
						JSONObject jsonObjecta = new JSONObject(
								publicHttpCallback(
										HTTP_SENDSTARTLOG,
										"code="
												+ logstr
												/*+ "&sch="
												+ login_code.getString(
														"sch_code", null)*/));

						if (jsonObjecta.getBoolean("success")) {
							sc.update_GO_BUS();

						}
					}
				}
				if (param != null) {
					JSONObject jsonObject = new JSONObject(publicHttpCallback(
							HTTP_INSERT_START, "code=" + param));
					String[] checkon = param.split("-");
					/*int check = 0;*/
					for (int i = 0; i < checkon.length; i++) {
						for (int j = 0; j < list.size(); j++) {
							if (list.get(j).stu_code.equals(checkon[i])) {
								sc.insert_GO_BUS(list.get(j).stu_name
										+ "의 서버전송 및 푸시발송 완료", 2);
								/*if (j > check) {
									check = j;
								}*/
								break;
							}

						}
					}
			/*		try {
						Log.i("dsdfds", list.get(check).Gob_Stu_Address);
						publicHttpCallback(
								HTTP_SENDSTARTSTATE,
								"code="
										+ code
										+ "&sth="
										+ login_code
												.getString("sch_code", null)
										+ "&order="
										+ list.get(check).Gob_Stu_Order
										+ "&msg="
										+ list.get(check).Gob_Stu_Address
										+ "&rank=" + "1");
					} catch (Exception e) {
						sc.insert_GO_BUS("등원상태 갱신푸시발송실패", 3);
					}*/
					sc.insert_GO_BUS("등원상태 갱신푸시발송성공", 2);
					param = null;
					onNetworkCallback(SUBSUCCESS, msg);
				} else {
					param = null;
					onNetworkCallback(SUBSUCCESS, msg);
				}
			} else {

				sc.insert_GO_BUS("네트워크상태 통신 불가 와이파이연결 안됨", 3);
				onNetworkCallback(SUBSUCCESS, "aset");
			}
		} catch (Exception e) {
			onNetworkCallback(SUBSUCCESS, "");
			sc.insert_GO_BUS("서버통신오류(서버문제)" + e.toString(), 3);
		}
		;
	}

	protected void threeThread() { // GCM보내기 스레드
		// TODO Auto-generated method stub
		try {

			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_INSERT_START, "code=" + list.get(changcode).stu_code));
			list.get(changcode).checkon = true;
			onNetworkCallback(THREESUCCESS, "");

		} catch (Exception e) {
			onNetworkCallback(THREESUCCESS, "");
		}
		;
	}

	protected void fourThread() { // GCM보내기 스레드
		// TODO Auto-generated method stub
		try {
			publicHttpCallback(
					HTTP_SENDSTARTSTATE,
					"code=" + code + "&sth="
							+ login_code.getString("sch_code", null)
							+ "&order=" +"0"
							+ "&msg=" + "등원버스가 운행을 마쳤습니다."
							+ "&rank=" + "0");
		} catch (Exception e) {
			sc.insert_GO_BUS("등원상태 갱신푸시발송실패", 3);
		}
		onNetworkCallback(END, "");
	}

	class StartAdapter extends ArrayAdapter<String> {

		public StartAdapter() {
			super(Start_ScanMode.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			StartHolder startHolder;
			final int pos = position;
			if (convertView == null) {
				startHolder = new StartHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.start_scanmode_row, null);
				int width = ((gridView.getWidth()) / 5);
				int height = ((gridView.getWidth()) / 5);
				startHolder.ll = (LinearLayout) convertView
						.findViewById(R.id.START_SCANMODE_LL);
				startHolder.ll.setLayoutParams(new LinearLayout.LayoutParams(
						width, height));

				startHolder.textView = (TextView) convertView
						.findViewById(R.id.START_SCANMODE_ROW);
				convertView.setTag(startHolder);
			} else {
				startHolder = (StartHolder) convertView.getTag();
			}
			startHolder.textView.setText(list.get(position).stu_name);
			if (list.get(position).checkon) {
				if (onoff) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_on);
				} else {
					Resources res = getResources();
					AnimationDrawable drawable = (AnimationDrawable) res
							.getDrawable(R.drawable.selectitemdel);
					startHolder.ll.setBackground(drawable);
					drawable.start();
				}
			} else {
				startHolder.ll
						.setBackgroundResource(R.drawable.selectitem_blue_off);
			}
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Start_ScanMode.this);
					builder.setMessage(
							list.get(pos).stu_name + "어린이를 탑승상태로 변경하시겠습니까?")
							.setCancelable(false)
							.setPositiveButton("탑승",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											changcode = pos;
											startThread(3);
										}
									})
							.setNegativeButton("취소",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();
				}
			});
			return convertView;
		}
	}

	class StartHolder {
		TextView textView;
		LinearLayout ll;
	}

	class LogAdapter extends ArrayAdapter<String> {

		public LogAdapter() {
			super(Start_ScanMode.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return loglist.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			TextView tv;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.logitem,
						null);
				tv = (TextView) convertView.findViewById(R.id.logitem_tv);
				convertView.setTag(tv);
			} else {
				tv = (TextView) convertView.getTag();
			}
			tv.setText(loglist.get(position));
			return convertView;
		}

	}

}
